package com.android.lovely.ui.chat

import android.os.Bundle
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.adapter.FragmentStateAdapter
import coil.load
import com.android.lovely.R
import com.android.lovely.const.ChatStyleChange
import com.android.lovely.data.DialogueStyle
import com.android.lovely.data.HomeTabData
import com.android.lovely.databinding.ActivityDialogueBinding
import com.android.lovely.ext.ColorUtils.calculateColor
import com.android.lovely.ext.MessageHelper.applyMessageWithStyle
import com.android.lovely.framework.BaseMvvmActivity
import com.android.lovely.manager.KVStore
import com.android.lovely.ui.widget.FontSizeSelector
import com.google.android.material.tabs.TabLayoutMediator
import com.kotlin.extensions.bus.FlowBus
import com.kotlin.extensions.bus.post
import com.kotlin.extensions.view.ViewExt.addStatusBarMarginTop
import com.kotlin.extensions.view.ViewExt.clickable
import kotlinx.coroutines.launch


/**
 *
 * @author why
 * @date 2025/3/30 20:43
 */
class ChatDialogueSettingActivity : BaseMvvmActivity<ActivityDialogueBinding, ChatStyleViewModel>() {

    private val fontSizes = arrayOf(13, 15, 17, 19, 21)

    val adapter by lazy {
        ChatAdapter(this)
    }

    // 字体选择器
    private lateinit var fontSizeSelector: FontSizeSelector


    override fun initView(savedInstanceState: Bundle?) {
        mBinding.ivLeft.clickable {
            finish()
        }
        val backgroundImage = intent.getStringExtra("bg")
        mBinding.bgImg.load(backgroundImage) { crossfade(true) }
        mBinding.ivReset.clickable {
            viewModel.resetStyle()
        }
        mBinding.save.clickable {
            viewModel.saveStyle()
            FlowBus.post(ChatStyleChange())
            finish()
        }

        initFontSize()

        mBinding.llTop.addStatusBarMarginTop()
        mBinding.bgImg.addStatusBarMarginTop()
        mBinding.viewPager.adapter = adapter

        mBinding.viewPager.offscreenPageLimit = adapter.itemCount
        TabLayoutMediator(
            mBinding.llTabLayout,
            mBinding.viewPager,
            getTabConfigurationStrategy()
        ).attach()
        adapter.notifyDataSetChanged()


        updateUserStyle(viewModel.defaultStyle.user)
        updateRoleStyle(viewModel.defaultStyle.role)
       lifecycleScope.launch {
           viewModel.updateFlow.collect {
               if(it.first) {
                   updateUserStyle(it.second)
               } else {
                   updateRoleStyle(it.second)
               }
           }
       }
    }

    private fun updateUserStyle(style: DialogueStyle) {
        mBinding.right.helper.backgroundColor =
            style.backgroundColor.calculateColor(style.backgroundColorAlpha)
        mBinding.right.text = "user“Preview text effects”*smile*".applyMessageWithStyle(style, true)
    }

    private fun updateRoleStyle(style: DialogueStyle) {
        mBinding.left.helper.backgroundColor =
            style.backgroundColor.calculateColor(style.backgroundColorAlpha)
        mBinding.left.text = "Role *Looks up and smiles* “You can edit the following information to set the font effect”".applyMessageWithStyle(style, true)
    }

    private fun initFontSize() {
        // 创建停靠点列表
        val stopPoints = listOf(mBinding.line1, mBinding.line2, mBinding.line3, mBinding.line4, mBinding.line5)

        // 初始化字体大小选择器
        fontSizeSelector = FontSizeSelector(
            parent = mBinding.fontSizeLayout,
            round = mBinding.round,
            line = mBinding.line,
            stopPoints = stopPoints
        )
        // 设置字体大小变化监听器
        fontSizeSelector.setOnSizeSelectedListener { index ->
            // 更新示例文本大小
            updateTextSize(index)
        }

        val fonts = KVStore.talkStyle.user.fontSize
        val index = fontSizes.indexOf(fonts)
        // 默认选中中间大小
        fontSizeSelector.setSelectedPosition(index)
    }

    private fun getTabConfigurationStrategy() =
        TabLayoutMediator.TabConfigurationStrategy { tab, position ->
            tab.text = adapter.getTitle(position)
        }

    /**
     * 更新文本大小
     */
    private fun updateTextSize(index: Int) {
        val size = fontSizes[index]
        viewModel.updateFontSize(size)
    }
}

class ChatAdapter(activity: FragmentActivity) : FragmentStateAdapter(activity) {

    private val tabs by lazy {
        mutableListOf(
            HomeTabData(null, activity.getString(R.string.role)),
            HomeTabData(null, activity.getString(R.string.user)),
        )
    }


    override fun getItemCount(): Int {
        return tabs.size
    }

    fun getTitle(position: Int): String {
        return tabs[position].roleName
    }

    override fun createFragment(position: Int): Fragment {
        return ChatStyleFragment().apply {
            arguments = bundleOf("id" to position)
        }
    }


}
